package com.cheng.im.gateway.mq;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

@Slf4j
public class MqFactory {

    private static ConcurrentHashMap<String, DefaultMQPushConsumer> consumerMap = new ConcurrentHashMap<>();

    public static DefaultMQPushConsumer getMQPushConsumer(
            String namesrvAddr, String top, String tag, String consumerGroup) {
        DefaultMQPushConsumer consumer = consumerMap.get(top);
        if(consumer == null){
            consumer = new DefaultMQPushConsumer(consumerGroup);
            consumer.setNamesrvAddr(namesrvAddr);
            try {
                consumer.subscribe(top, tag);
            } catch (MQClientException e) {
                log.error("===============消息监听订阅主题出错================");
                throw new RuntimeException(e);
            }
            consumerMap.put(top, consumer);
        }
        return consumer;
    }

    public static DefaultMQPushConsumer getMQPushConsumer(String namesrvAddr, String top, String consumerGroup) {
        DefaultMQPushConsumer consumer = consumerMap.get(top);
        if(consumer == null){
            consumer = new DefaultMQPushConsumer(consumerGroup);
            consumer.setNamesrvAddr(namesrvAddr);
            try {
                consumer.subscribe(top, "*");
            } catch (MQClientException e) {
                log.error("===============消息监听订阅主题出错================");
                throw new RuntimeException(e);
            }
            consumerMap.put(top, consumer);
        }
        return consumer;
    }

    public static void destroy(){
        consumerMap.values().stream().forEach(DefaultMQPushConsumer::shutdown);
    }
}
